/*********************************************************
 * CS 252 Project 6
 * Android VOIP App
 * 
 * RingerConnection Class
 * 
 * This class maintains a connection between a
 * RinverClient and a RingerServer
 *********************************************************/

package com.avp;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

public class RingerConnection implements Runnable {
	String _user;
	Socket _socket;
	PrintWriter _out;
	BufferedReader _in;
	boolean _connected;
	public boolean running=true;
	String _response;
	Activity2 parent;
	Voice voice;
	//////////////////
	// Constructors //
	//////////////////
	public RingerConnection (Socket socket, Activity2 parent) {
		_user = "";
		_socket = socket;
		try {
			_out = new PrintWriter(_socket.getOutputStream(), true);
			_in = new BufferedReader(new InputStreamReader(_socket.getInputStream()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		_connected = false;
		_response = "";
		this.parent=parent;
	}
	
	//////////////
	// Mutators //
	//////////////
	public void setResponse(String response) {
		//response should be "accept" or "reject"
		_response = response;
	}
	
	/////////////
	// Methods //
	/////////////
	public void run() {
		try {
			
			String input;
			while (running) {
				if (_in.ready()) {
					input = _in.readLine();
					
					if (input.equals("Calling")) {
						//TODO: update GUI to show someone is calling
				
						Log.d("ring", "accepting call");
					
						parent.h.sendEmptyMessage(0);
						//parent.incomingCall();
						
						//this.setResponse("accept");

						
						//GUI should display accept and reject buttons
						//have those buttons call setResponse("accept"); and setResonse("reject");
						_user = _in.readLine();
						_connected = true;
						
						// wait for 	"accept" or "reject"
						while(_response.equals("")) {
							//Log.d("ring", "actually working");
							try {		
								//Thread.sleep(500);
								
								} catch (Exception e) {
								e.printStackTrace();
								
							}
						}
						if (_response.equals("accept"))
						{
						   voice = new Voice();
							//Log.d("ring", _socket.getInetAddress()+"   "+_socket.getPort());
							voice.startConnection(_socket.getInetAddress(),8999);
						
						}
						Log.d("ring", "sending response");
						_out.println(_response);
					
					if (input.equals("End call")){
                        _connected = false;
					}
				}
				}
				if (_socket.isClosed()) {
					_connected = false;
					return;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
